<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Hash;
use Log;
use Encore\Admin\Facades\Admin;
use App\Models\Device;

use App\Models\Cabinet;
use App\Models\CabinetData;
use App\Models\CabinetDataSecond;
use App\Models\CabinetPoint;
use App\Models\ProjectUser;
use App\Models\Project;
use App\Models\Company;
use App\Models\CabinetAlarmLog;
use App\Models\CabinetAlarm;
use App\Models\CabinetLiveText;
use App\Handlers\WeconHandler;
use App\Models\xfProject;
use App\Models\Points;
use App\Models\Floors;
use Dcat\EasyExcel\Excel;
use Illuminate\Support\Facades\Redis;

//20210419
class WeikongController extends Controller
{
    public function DeviceDetail(Request $request){
        $param = $request->all();
        $role = Db::table('admin_role_users')->where(['user_id'=>$param['adminId']])->first();
        if($role->role_id==8){
            $Floors = Floors::where(['id'=>$param['deviceId']])->first();
            $Cabinet = xfProject::where('id',$Floors['project_id'])->get()->toArray();
            $Cabinet['companyname'] = '厦门城力只能设备';
            $Cabinet['projectname'] = '在线项目';
            $Cabinet['name'] = $Floors['name'];
            $Cabinet['image'] = $Floors['image'];
        }else{
            $Cabinet = Cabinet::where(['id'=>$param['deviceId']])->first();
            $Cabinet['tab'] = Cabinet::where(['pid'=>$param['deviceId']])->get()->toArray();
            //项目
            $project = Project::where(['projectId'=>$Cabinet['projectId']])->first();
            //公司
            $company = Company::where(['companyId'=>$project['companyId']])->first();
            $Cabinet['companyname'] = $company['name'];
            $Cabinet['projectname'] = $project['projectname'];
            $time = date('Y-m-d H:i:s');
            //运行天数
            $Cabinet['date'] = floor((strtotime($time)-strtotime($Cabinet['created_at']))/86400);
            $check = WeconHandler::getBoxStatus($Cabinet['machine_code']);
            if ($check) {
                $Cabinet['status'] = 'online';
            } else {
                $Cabinet['status'] = 'offline';
            }
        }
        return $Cabinet;
    }
    
    public function getRealtimeDataByMiniGroup(Request $request){
        $param = $request->all();
        return response()->json(['code'=>0, 'data' => '', 'msg' => 'no update']);
    }

    public function getDeviceStatusCharts(Request $request){
        $param = $request->all();
        $projectIds = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
        //地图数据相关
        $projects = Project::select(['projectId','projectname', 'lat', 'lng'])->whereIn('projectId', $projectIds)->get()->toArray();
        // print_r($projects);die;
        // $mapList = [];
        $provinces = [];
        $urlPrefix = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=';
        $urlSuffix = '&key=efc9084469fb60d4aaef0dfe90c7bdf5&extensions=base';
        // $AlarmProject = []; //报警项目
        // $Project = []; //在线项目
        // $address = [];
        foreach ($projects as $one) {
            if (!empty($one['lat'])  && !empty($one['lng'])) {
                // $address[$one['projectname']] = array($one['lng'],$one['lat']);
                $t['name'] = $one['projectname'];
                $t['lat'] = $one['lat'];
                $t['lng'] = $one['lng'];
                $t['id'] = $one['projectId'];
                $a['name'] = $one['projectname'];
                $undealLogNum = CabinetAlarmLog::where('project_id', $one['projectId'])->where('status', CabinetAlarmLog::STATUS_NO)->count();
                $boxId = Cabinet::where('project_id', $one['projectId'])->where('pid', 0)->value('id');
                $t['url'] = $boxId ? admin_url('cabinet-children').'/'.$boxId : '';
                $a['content'] = $boxId ? 'cabinet-children/'.$boxId : 'project/'.$one['projectId'];
                // if ($undealLogNum > 0) {
                //     $t['icon'] = url('icon/warning.png');
                //     $a['value'] = 133;
                //     array_push($AlarmProject, $a);
                // } else {
                //     $t['icon'] = '';
                //     $a['value'] = 133;
                //     array_push($Project, $a);
                // }
                // array_push($mapList, $t);
                if (intval($one['lat']) && intval($one['lng'])) {
                    $url = $urlPrefix.$one['lng'].','.$one['lat'].$urlSuffix;
                    $rr = Request_curl($url, false, 0, 0);
                    $r = json_decode($rr, true);
                    if ($r['status'] && $r['regeocode']['addressComponent']['province']) {
                        $oneP = $r['regeocode']['addressComponent']['province'];
                        array_push($provinces, $oneP);
                    }
                }
            }
        }
        // $data['mapList'] = $mapList;
        // $data['address'] = $address;
        // $data['alarmproject'] = $AlarmProject;
        // $data['inlineproject'] = $Project;
        //省份分布
        $tmpProvince = array_count_values($provinces);
        $provinceData = [];
        foreach ($tmpProvince as $pname => $pnum) {
            $tmpOne['value'] = $pnum;
            $tmpOne['name'] = $pname;
            array_push($provinceData, $tmpOne);
        }
        $data['provinceList']['num'] = count($tmpProvince);
        // $data['provinceList']['data'] = json_encode($provinceData);
        $data['provinceList']['data'] = $provinceData;

        //在线设备数据
        $boxes = Cabinet::whereIn('project_id',$projectIds)->where('pid', 0)->pluck('machine_code', 'id')->toArray();
        $total = count($boxes);
        $online = 0;
        $offline = 0;
        if ($boxes) {
            foreach ($boxes as $id => $machineCode) {
                $check = WeconHandler::getBoxStatus($machineCode);
                if ($check) {
                    $online++;
                } else {
                    $offline++;
                }
            }
        }   
        $data['boxStatus'] = array(array('value'=>$online,'name'=>$online.'在线'),array('value'=>$offline,'name'=>$offline.'离线'));
        //报警记录
        // $alertLogList = CabinetAlarmLog::select('alarm_name', 'created_at')->whereIn('project_id',$projectIds)->orderBy('created_at', 'desc')->take(10)->get()->toArray();
        // foreach ($alertLogList as &$one) {
        //     $one['created_at'] = $one['created_at'];
        //     $one['msg'] = $one['alarm_name'];
        // }
        // $data['alertLogList'] = $alertLogList;
        if($data){
            return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
        }else{
            return response()->json(['code'=>0, 'data' => '', 'msg' => 'success']);
        }
    }
    public function Identity(Request $request){
        $param = $request->all();
        $projectIds = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
        $projects = Cabinet::select(['id as value','name as text'])->whereIn('project_id', $projectIds)->where(['pid'=>0])->get()->toArray();
        $arr = array('value'=>0,'text'=>'请选择云盒');
        array_unshift($projects,$arr);
        if($projects){
            return response()->json(['code'=>1, 'data' => $projects, 'msg' => 'success']);
        } else {
            return response()->json(['code'=>0, 'data' => $arr, 'msg' => 'no update']);
        }
    }
    public function geiDevicePoiont(Request $request){
        $param = $request->all();
        $points = Cabinet::select(['id as value','name as text'])->where(['pid'=>$param['boxId']])->get()->toArray();
        $arr = array('value'=>0,'text'=>'请选择设备');
        array_unshift($points,$arr);
        if($points){
            return response()->json(['code'=>1, 'data' => $points, 'msg' => 'success']);
        } else {
            return response()->json(['code'=>0, 'data' => $arr, 'msg' => 'no update']);
        }
    }
    public function getPointsByCabinetId(Request $request){
        $param = $request->all();
        $data['points1'] = CabinetPoint::select('name as text', 'alias as value')->where('cabinet_id', $param['id'])->get()->toArray();
        $data['points2'] = $data['points1'];
        $data['points'] = $data['points1'];
        $arr1 = array('value'=>0,'text'=>'请选择X轴');
        $arr2 = array('value'=>0,'text'=>'请选择Y轴');
        $arr3 = array('value'=>0,'text'=>'请选择数据点');
        array_unshift($data['points1'],$arr1);
        array_unshift($data['points2'],$arr2);
        array_unshift($data['points'],$arr3);
        return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
    }
    public function getChartDataByPoint(Request $request){
        $param = $request->all();
        $end = strtotime($param['end']);
        $start = strtotime($param['start']);

        $d = CabinetDataSecond::getJsonDataList($param['cabinetId'], [$param['x'], $param['y']], $start, $end);
        $xData = [];
        $yData = [];
        foreach ($d as $one) {
            $one = json_decode( json_encode( $one ),true);
            $xData[] = round($one[$param['x']], 3);
            $time = date("H:i:s", $one['created_time']);
            // $yData[] = round($one[$param['y']], 3);
            $yData[] = ['time' => $time, 'value' => round($one[$param['y']], 3)];
        }
        $data['xData'] = $xData;
        $data['yData'] = $yData;
        return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
    }
    public function  weikonglist(){
        $body['resultBody']['device'] = Db::table('xfy_device')->where(['device_type'=>6])->get()->toArray();
        $body['resultCode'] =1;
        return $body;
    }
    public function getweikong(Request $request){
        $info = $request->all();
        // $body['resultBody']['project'] = Db::table('xfy_device')->where(['xfy_device.deviceId'=>$info['deviceId']])
        // ->join('xfy_project','xfy_project.projectId','=','xfy_device.projectId')
        // ->first();
        $body['resultBody'] = Db::table('xfy_cabinet')->where(['pid'=>$info['deviceId']])->groupBy('group')->get()->toArray();
        $body['resultCode'] = 1;
        return $body;
    }

    public function weikongdetail(Request $request){
        $info = $request->all();
        $pname=Db::table('xfy_device')->where(['deviceId'=>$info['pid']])->select('gatewayId')->get()->toArray();
         $list = Db::table('xfy_weikong')->where(['address'=>$info['group'],'pname'=>$pname[0]->gatewayId])->groupBy('gatewayId')->get()->toArray();
         // print_r($list);die;
         $arr = array();
         foreach ($list as $key => &$value) {
            $res = Db::table('xfy_weikong')->where(['gatewayId'=>$value->gatewayId])->orderBy('id','DESC')->first();
            $arr[$key]['gatewayId'] = $res->gatewayId;
            $arr[$key]['value'] = $res->value;
         }
         $body['resultBody'] = $arr;
        $body['resultCode'] = 1;
        return $body;
    }

    public function getWeikongLog(Request $request){
        $info = $request->all();
        $body['resultBody'] = Db::table('xfy_weikong')->where(['gatewayId'=>$info['id']])->orderBy('id','desc')->get()->toArray();
        if($body['resultBody']){
               $body['resultCode'] = 1;
        }else{
            $body['resultCode'] = 0;
            $body['resultMsg'] = '暂无数据';
        }
        return $body;
    }

    //*****************************************

    public function getBoxList(Request $request){
        $param = $request->all();
        $adminProjects = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
        $boxes = Cabinet::whereIn('project_id', $adminProjects)->where('pid', 0)->get()->toArray();
        if ($boxes) {
            foreach ($boxes as &$oneBox) {
                $oneBox['project_name'] = Project::where('projectId', $oneBox['project_id'])->value('projectname');
            }
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $boxes]);
        } else {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => []]);
        }
    }

    public function getCabinetsByBox(Request $request){
        $param = $request->all();
        $cabinets = Cabinet::where('pid', $param['boxId'])->get()->toArray();
        if ($cabinets) {
            foreach ($cabinets as &$oneCabinet) {
                $oneCabinet['project_name'] = Project::where('projectId', $oneCabinet['project_id'])->value('projectname');
            }
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $cabinets]);
        } else {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => []]);
        }
    }

    public function getDataByCabinet(Request $request){
        $param = $request->all();
        $data = [];
        $points = CabinetPoint::where('cabinet_id', $param['cabinetId'])->pluck('name','alias');
        $fields = array_keys($points->toArray());
        $values = CabinetDataSecond::getJsonDataOne($param['cabinetId'], $fields);
        if (empty($values)) {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => []]);
        }
        $noShowPoint = CabinetPoint::where('cabinet_id', $param['cabinetId'])->where('realtime_show', 0)->pluck('alias')->toArray();
        foreach ($points as $alias => $name) {
            if (in_array($alias, $noShowPoint)) {
                continue;
            }
            $one['cabinetId'] = $param['cabinetId'];
            $one['alias'] = $alias;
            $one['name'] = $name;
            $one['value'] = $values[$alias];
            array_push($data, $one);
        }

        $extraText = CabinetLiveText::getTextCache($values);
        $liveText = [];
        if ($extraText) {
            foreach ($extraText as $oneText) {
                $kk = array_keys($oneText);
                $kk = reset($kk);

                $oneLiveText['cabinetId'] = $param['cabinetId'];
                $oneLiveText['alias'] = $kk;
                $oneLiveText['name'] = $oneText[$kk]['name'];
                $oneLiveText['value'] = '';
                array_push($liveText, $oneLiveText);
            }
        }
        if ($liveText) {
            $data = array_merge($liveText, $data);
        }
        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $data]);
    }

    public function getRealtimeDataByCabinet(Request $request){
        $param = $request->all();
        $data = [];
        $newestCacheKey = Cabinet::CACHE_KEY_.$param['cabinetId'];
        $newestCache = Redis::get($newestCacheKey);
        if (empty($newestCache)) {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => []]);
        }
        $points = CabinetPoint::select(['id', 'alias', 'name', 'units', 'decimal'])->where('cabinet_id', $param['cabinetId'])->get()->keyBy('alias')->toArray();
        $newestData = json_decode($newestCache, true);
        $noShowPoint = CabinetPoint::where('cabinet_id', $param['cabinetId'])->where('realtime_show', 0)->pluck('alias')->toArray();
        if ($noShowPoint) {
            foreach ($noShowPoint as $oneNoShow) {
                unset($newestData[$oneNoShow]);
            }
        }

        foreach ($newestData as $alias => $value) {
            $one['cabinetId'] = $param['cabinetId'];
            $one['alias'] = $alias;
            $one['name'] = isset($points[$alias]['name']) ? $points[$alias]['name'] : $alias;
            $one['value'] = $value;
            array_push($data, $one);
        }
        $extraText = CabinetLiveText::getTextCache($newestData);
        $liveText = [];
        if ($extraText) {
            foreach ($extraText as $oneText) {
                $kk = array_keys($oneText);
                $kk = reset($kk);

                $oneLiveText['cabinetId'] = $param['cabinetId'];
                $oneLiveText['alias'] = $kk;
                $oneLiveText['name'] = $oneText[$kk]['name'];
                $oneLiveText['value'] = '';
                array_push($liveText, $oneLiveText);
            }
        }
        if ($liveText) {
            $data = array_merge($liveText, $data);
        }
        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $data]);
    }
    // public function getHistory(Request $request){
    //     $param = $request->all();
    //     $projectIds = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
    // }
    public function getHistoryByPoint(Request $request){
        $param = $request->all();
        $page = isset($param['page']) ? $param['page'] : null;
        $size = isset($param['size']) ? $param['size'] : null;
        // $date = isset($param['date']) ? $param['date'] : date('Y-m-d');

        // $start = strtotime($date);
        // $end = time();
        $start = intval($param['start']/1000);
        $end = intval($param['end']/1000);

        $points = CabinetPoint::where('cabinet_id', $param['cabinetId'])->where('history_show', 1)->pluck('name','alias')->toArray();
        $keys = array_keys($points);

        $tt = array_merge(['created_time' => '时间'], $points);
        $title = [];
        foreach ($tt as $k => $v) {
            $oneTitle['title'] = $v;
            $oneTitle['key'] = $k;
            array_push($title, $oneTitle);
        }
        // error_log("title = ".print_r($title,1)."\n",3,'/tmp/joker.log');
        $cabinet = Cabinet::find($param['cabinetId']);
        $d = CabinetDataSecond::getJsonDataListPaging($param['cabinetId'], $keys, $start, $end, $page, $size);

        $xData = [];
        $data['currentPage'] = intval($page);
        $data['title'] = $title;
        $data['data'] = [];
        $title = [];
        foreach ($d as $v) {
            $one = [];
            $v = json_decode( json_encode( $v ),true);
            $xData[] = date("H:i:s", $v['created_time']);
            $v['created_time'] = date("Y-m-d H:i:s", $v['created_time']);
            array_push($data['data'], $v);

            foreach ($points as $onePointAlias => $onePointName) {
                if (isset($v[$onePointAlias])) {
                    $$onePointAlias[] = $v[$onePointAlias];
                } else {
                    $$onePointAlias[] = 0;
                }
            }
        }
        $legend = [];
        $series = [];
        foreach ($points as $onePointAlias => $onePointName) {
            $legend[$onePointAlias] = $onePointName;
            $oneSeries['name'] = $onePointName;
            $oneSeries['type'] = 'line';
            $oneSeries['data'] = isset($$onePointAlias) ? $$onePointAlias : [];
            $series[$onePointAlias] = $oneSeries;
        }
        $data['xData'] = $xData;
        $data['legend'] = $legend;
        $data['series'] = $series;

        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $data]);
    }

    public function addBox(Request $request){
        // return response()->json(['code'=>0, 'msg' =>'添加失败，请重试']);
        $param = $request->all();
        $boxId = WeconHandler::getBoxIdByMachineCode($param['machineCode']);
        if (empty($boxId)) {
            return response()->json(['code'=>0, 'msg' =>'无效的维控机器码']);
        }
        $check = Cabinet::where('machine_code', $param['machineCode'])->first();
        if ($check) {
            return response()->json(['code'=>0, 'msg' =>'该云盒已存在']);
        }

        $cabinet = new Cabinet();
        $cabinet->name = $param['name'];
        $cabinet->project_id = $param['projectId'];
        $cabinet->machine_code = $param['machineCode'];
        if (isset($param['address']) && !empty($param['address'])) {
            $cabinet->address = $param['address'];
        }
        $cabinet->box_id = $boxId;
        if ($cabinet->save()) {
            Cabinet::syncWeikong($cabinet->id);
            return response()->json(['code'=>1, 'msg' =>'添加成功']);
        } else {
            return response()->json(['code'=>0, 'msg' =>'添加失败，请重试']);
        }
    }

    public function downloadHistoryByPoint(Request $request){
        $param = $request->all();
        $start = intval($param['start']/1000);
        $end = intval($param['end']/1000);

        $points = CabinetPoint::where('cabinet_id', $param['cabinetId'])->where('history_show', 1)->pluck('name','alias')->toArray();
        $keys = array_keys($points);

        $d = CabinetDataSecond::getJsonDataList($param['cabinetId'], $keys, $start, $end);

        $data = [];
        $header = array_merge(['created_time' => '时间'], $points);
        foreach ($d as $v) {
            $v = json_decode( json_encode( $v ),true);
            $v['created_time'] = date("Y-m-d H:i:s", $v['created_time']);
            array_push($data, $v);
        }
        $filename = date('YmdHis').'.xlsx';
        $filePath = public_path('cabinet-excel');
        
        $res = Excel::export($data)->headings($header)->store($filePath.'/'.$filename);
        if ($res) {
            $url = url('cabinet-excel/'.$filename);
            return response()->json(['code'=>1, 'msg' =>'生成成功', 'data' => $url]);
        } else {
            return response()->json(['code'=>1, 'msg' =>'生成失败', 'data' => '']);
        }
    }

    public function getCabinetAlarmLogs(Request $request){
        $param = $request->all();
        $page = isset($param['page']) ? $param['page'] : null;
        $size = isset($param['size']) ? $param['size'] : null;
        $where = [];
        $wherea = [];
        if($param['time']!='请选择时间'){
            $where[] = ['created_at','>=',$param['time']];
        }
        if($param['value']!=''){
            $wherea[] = ['alarm_name','like','%'.$param['value'].'%'];
        }
        if($param['cabinetId']==0){
            $projectIds = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
            $cabinets = Cabinet::whereIn('project_id', $projectIds)->where($where)->where('pid','>','0')->pluck('id')->toArray();
            $points = CabinetPoint::whereIn('cabinet_id', $cabinets)->pluck('name', 'id')->toArray();
            $res = CabinetAlarmLog::whereIn('cabinet_id', $cabinets)->where($wherea)->orderBy('created_at', 'desc')->paginate($size, ['*'], 'page', $page)->toArray();
        }else{
            $cabinets = Cabinet::where('pid', $param['cabinetId'])->where($where)->pluck('id')->toArray();
            $points = CabinetPoint::whereIn('cabinet_id', $cabinets)->pluck('name', 'id')->toArray();
            $res = CabinetAlarmLog::whereIn('cabinet_id', $cabinets)->where($wherea)->orderBy('created_at', 'desc')->paginate($size, ['*'], 'page', $page)->toArray();
        }
        if ($res['data']) {
            foreach ($res['data'] as &$one) {
                $one['point_name'] = $points[$one['point_id']];
                $one['status_text'] = CabinetAlarmLog::STATUS_TEXT[$one['status']];
                $one['alarm_level_text'] = CabinetAlarm::LEVEL_TEXT[$one['alarm_level']];
            }
        }

        $list['currentPage'] = $res['current_page'];
        $list['list'] = $res['data'];
        $list['lastPage'] = $res['last_page'];
        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data'=>$list]);
    }

    public function dealCabinetAlarmLog(Request $request){
        $param = $request->all();
        $idStr = $param['logIds'];
        $logIds = explode(',', $idStr);
        $logs = CabinetAlarmLog::whereIn('id', $logIds)->get();
        foreach ($logs as $oneLog) {
            $oneLog->status = CabinetAlarmLog::STATUS_YES;
            $oneLog->operator = $param['adminId'];
            $oneLog->save();
        }
        return response()->json(['code'=>1, 'msg' =>'处理成功']);
    }

    public function getRealtimeBaseByCabinet(Request $request){
        $param = $request->all();
        $cabinet = Cabinet::find($param['cabinetId']);

        $points = CabinetPoint::where('cabinet_id', $param['cabinetId'])->pluck('name','alias')->toArray();
        $fields = array_keys($points);

        $start = strtotime("-1 hours");
        $d = CabinetDataSecond::getJsonDataList($param['cabinetId'], $fields, $start);

        $xData = [];
        foreach ($d as $v) {
            $v = json_decode( json_encode( $v ),true);
            $xData[] = date("H:i:s", $v['created_time']);
            $v['created_time'] = date("Y-m-d H:i:s", $v['created_time']);
            foreach ($points as $onePointAlias => $onePointName) {
                if (isset($v[$onePointAlias])) {
                    $$onePointAlias[] = $v[$onePointAlias];
                } else {
                    $$onePointAlias[] = 0;
                }
            }
        }
        $legend = [];
        $series = [];
        foreach ($points as $onePointAlias => $onePointName) {
            $legend[$onePointAlias] = $onePointName;
            $oneSeries['name'] = $onePointName;
            $oneSeries['type'] = 'line';
            $oneSeries['data'] = isset($$onePointAlias) ? $$onePointAlias : [];
            $series[$onePointAlias] = $oneSeries;
        }
        $data['xData'] = $xData;
        $data['legend'] = $legend;
        $data['series'] = $series;

        return response()->json(['code'=>1, 'data' => $data, 'msg' =>'查询成功']);

    }
    public function getRealtimeNowByCabinet(Request $request){
        $param = $request->all();
        $cabinet = Cabinet::find($param['cabinetId']);

        $newestCacheKey = Cabinet::CACHE_KEY_.$param['cabinetId'];
        $newestCache = Redis::get($newestCacheKey);
        if (empty($newestCache)) {
            return response()->json(['code'=>1, 'data' => [], 'msg' =>'查询成功']);
        }

        $points = CabinetPoint::where('cabinet_id', $param['cabinetId'])->pluck('name','alias')->toArray();
        $nowData = json_decode($newestCache,true);
        foreach ($nowData as $alias => $value) {
            if (!isset($points[$alias])) {
                unset($nowData[$alias]);
            }
        }
        $data['data'] = $nowData;
        $data['time'] = date("H:i:s");
        return response()->json(['code'=>1, 'data' => $data, 'msg' =>'查询成功']);
    }

    public function syncBox(Request $request){
        $param = $request->all();
        $box = Cabinet::find($param['boxId']);
        if (empty($box['machine_code'])) {
            return response()->json(['code'=>0, 'msg' =>'无效的维控机器码']);
        }
        Cabinet::syncWeikong($param['boxId']);
        return response()->json(['code'=>1, 'msg' =>'同步成功']);
    }

    public function getCabinetPoints(Request $request)
    {
        $param = $request->all();

        $nowData = [];
        $newestCacheKey = Cabinet::CACHE_KEY_.$param['cabinetId'];
        $newestCache = Redis::get($newestCacheKey);
        if ($newestCache) {
            $nowData = json_decode($newestCache, true);
        }

        $points = CabinetPoint::select(['id', 'alias', 'name', 'units', 'decimal', 'writable'])->where('cabinet_id', $param['cabinetId'])->get()->toArray();

        foreach ($points as $one) {
            $one['value'] = isset($nowData[$one['alias']]) ? $nowData[$one['alias']] : 0;
            if ($one['decimal']) {
                $one['value'] = round($nowData[$one['alias']] / pow(10, intval($one['decimal'])), 3);
            }
        }

        return response()->json(['code'=>1, 'data' => $points, 'msg' =>'查询成功']);
    }

    public function setCabinetPoint(Request $request)
    {
        $param = $request->all();
        $tmp = explode('_', $param['alias']);
        $monitorId = end($tmp);
        $res = WeconHandler::setData($monitorId, $param['value']);
        if (!$res && $res !== false) {
            return response()->json(['code'=>1, 'msg' => 'success']);
        } else {
            if (isset($res['error'])) {
                return response()->json(['code'=>0, 'msg' => $res['error']]);
            } else {
                return response()->json(['code'=>0, 'msg' => '修改失败']);
            }
        }
    }
}